package com.yupi.oj.controller;

import cn.hutool.core.bean.BeanUtil;
import com.yupi.oj.common.BaseResponse;
import com.yupi.oj.common.ErrorCode;
import com.yupi.oj.common.ResultUtils;
import com.yupi.oj.model.entity.User;
import com.yupi.oj.model.entity.VoucherOrder;
import com.yupi.oj.ojMQ.orderMQ.OrderMessageProducer;
import com.yupi.oj.service.UserService;
import com.yupi.oj.service.VoucherOrderService;
import com.yupi.oj.utils.RedisIdWorker;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;

@RestController
@RequestMapping("/voucher-order")
public class VoucherOrderController {
    @Resource
    private UserService userService;
    @Resource
    private RedisIdWorker redisIdWorker;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private OrderMessageProducer orderMessageProducer;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    //静态代码块中对其初始化
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setResultType(Long.class);
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
    }
    @PostMapping("seckill/{id}")
    public BaseResponse seckillVoucher(@PathVariable("id")Long voucherId, HttpServletRequest request) {
        VoucherOrder voucherOrder = new VoucherOrder();
        Long userId = userService.getLoginUser(request).getId();
        long orderId = redisIdWorker.nextId("order");
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString(), String.valueOf(orderId)
        );
        int i = result.intValue();
        if (i!=0){
            return ResultUtils.error(ErrorCode.OPERATION_ERROR,(i==1? "库存不足" : "每人限一张"));
        }
        voucherOrder.setVoucherId(voucherId);
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userId);
        orderMessageProducer.sendMessage(voucherOrder);
        return ResultUtils.success(orderId);
    }
}